<html>
  <head>
    <script src="https://cdn.socket.io/4.3.2/socket.io.min.js"></script>
    <script>
      const socket = io('http://localhost:3005');

      const CHAT_ROOM_NAME = 'chatRoom';
      let NICK_NAME = 'xf';

      socket.on('connect', function () {
        console.log('Connected');

        socket.emit('joinRoom', CHAT_ROOM_NAME);

        socket.on('message', function (msgContent) {
          const { nickName, message, isSystem } = msgContent;

          console.log('=========');
          console.log(nickName, message);
          let chat = document.getElementById('chat');
          if (isSystem) {
            chat.innerHTML = chat.innerHTML + `<p>${message}</p>`;
            return;
          }
          chat.innerHTML = chat.innerHTML + `<p>${nickName}: ${message}</p>`;
        });

        let sendMessage = function () {
          const message = document.getElementById('message').value;
          NICK_NAME = document.getElementById('nickName').value;

          socket.emit('sendMessage', {
            room: CHAT_ROOM_NAME,
            nickName: NICK_NAME,
            message: message,
          });
        };
        const sendBtn = document.querySelector('button');
        sendBtn.addEventListener('click', sendMessage);
      });
      socket.on('disconnect', function () {
        console.log('Disconnected');
      });
    </script>
  </head>

  <body>
    <div>
      <h1>Chat Room</h1>
      <div>
        <input type="text" id="nickName" />
        <input type="text" id="message" />
        <button>Send</button>
      </div>
      <div id="chat"></div>
    </div>
  </body>
</html>
